package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * TODO
     *      - 查询文章
     *
     * @param dto WmNewsPageReqDto
     * @return ResponseResult
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 1.检查查询参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.检查分页参数
        dto.checkParam();
        // 3.获取当前登录用户
        WmUser wmUser = WmThreadLocalUtil.getUser();
        // 4.分页条件设置
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        // 5.文章状态精确查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        // 6.频道列表精确查询
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        // 7.发布日期范围查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }
        // 8.关键字模糊查询
        if (dto.getKeyword() != null) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        // 9.查询当前用户发布的文章
        wrapper.eq(WmNews::getUserId, wmUser.getId());
        // 10.发布时间倒序排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 11.返回结果
        page(page, wrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * TODO
     *      - 发布文章
     *
     * @param dto WmNewsPageReqDto
     * @return ResponseResult
     */
    @Override
    @Transactional
    public ResponseResult submit(WmNewsDto dto) {
        // 1.校验参数
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getType() == -1) {
            dto.setType(null);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        List<String> images = dto.getImages();
        if (images != null && images.size() > 0) {
            wmNews.setImages(StringUtils.join(images, ","));
        }
        saveOrUpdateNews(dto, wmNews);
        // 3.如果是草稿
        if (dto.getStatus() == 0) {
            return ResponseResult.okResult(null);
        }
        // 关联内容素材关系
        List<String> imageList = getImages(dto);
        saveNewsMaterial(wmNews, imageList, WemediaConstants.WM_CONTENT_REFERENCE);
        // 关联封面素材关系
        savePageMaterial(dto, wmNews, imageList);
        /* // 异步调用审核
        wmNewsAutoScanService.autoScanWmNews(wmNews.getId()); */
        //调用延迟队列，添加任务
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());
        // 4.返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void savePageMaterial(WmNewsDto dto, WmNews wmNews, List<String> images) {
        List<String> imageList = dto.getImages();
        if (dto.getType() == null) {
            if (images.size() >= 1 && images.size() < 3) {
                imageList = images.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
            } else if (images.size() >= 3) {
                imageList = images.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(StringUtils.join(imageList, ","));
            updateById(wmNews);
        }
        saveNewsMaterial(wmNews, imageList, WemediaConstants.WM_COVER_REFERENCE);
    }

    private static List<String> getImages(WmNewsDto dto) {
        String content = dto.getContent();
        List<Map> list = JSON.parseArray(content, Map.class);
        List<String> imageList = new ArrayList<>();
        for (Map map : list) {
            if ("image".equals(map.get("type"))) {
                imageList.add(map.get("value").toString());
            }
        }
        return imageList;
    }

    /**
     * TODO
     *      - 根据id查询文章
     *
     * @param id id
     * @return ResponseResult
     */
    @Override
    public ResponseResult one(Integer id) {
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     * TODO
     *      - 根据id删除文章
     *
     * @param id id
     * @return ResponseResult
     */
    @Override
    @Transactional
    public ResponseResult delNews(Integer id) {
        // 1.校验参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.查询文章
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3.下架或者状态不为9（已发布）
        if (wmNews.getEnable() == 0 || wmNews.getStatus() != 9) {
            // 删除文章关联的素材
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
            // 删除文章
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
    }

    /**
     * TODO
     *      - 文章上下架
     *
     * @param dto WmNewsDto
     * @return ResponseResult
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        // 1.校验参数
        if (dto == null || dto.getId() == null || dto.getEnable() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.根据newsId查询news
        WmNews news = getById(dto.getId());
        // 3.文章不存在，返回结果
        if (news == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 4.文章没发布，返回结果
        if (news.getStatus() != WmNews.Status.PUBLISHED.getCode()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "未发布文章无法上下架");
        }
        // 5.修改文章enable
        news.setEnable(dto.getEnable());
        boolean flag = updateById(news);
        // 6.发送消息
        if (flag && news.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", news.getArticleId());
            map.put("enable", news.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            kafkaTemplate.send(WmNewsMessageConstants.ES_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
        }
       return null;
    }

    private void saveOrUpdateNews(WmNewsDto dto, WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        // 2.判断是否存在id
        if (dto.getId() != null) {
            // 删除已关联素材关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            // 修改文章
            updateById(wmNews);
        } else {
            // 新增文章
            save(wmNews);
        }
    }

    private void saveNewsMaterial(WmNews wmNews, List<String> imageList, Short type) {
        if (imageList != null && imageList.size() > 0) {
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                    Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, imageList));
            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.insertBatch(materialIds, wmNews.getId(), type);
        }
    }
}
